package com.asm.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author morningbear
 * @description 通过经纬度计算两点之间的距离
 * @date 2019/7/12
 */
@Slf4j
@Component
public class LocationalUtils {

    private static double EARTH_RADIUS = 6378.137;

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     *
     * @param lat1 纬度
     * @param lng1 经度
     * @param lat2 纬度
     * @param lng2 经度
     * @return 距离
     */
    public static double getDistance(double lat1, double lng1, double lat2, double lng2) {

        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double radLat = radLat1 - radLat2;
        double radLng = rad(lng1) - rad(lng2);
        double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(radLat / 2), 2) + Math.cos(radLat1) *
                Math.cos(radLat2) * Math.pow(Math.sin(radLng / 2), 2)));
        distance *= EARTH_RADIUS;
        distance = Math.round(distance * 10000d) / 10000d;
        distance *= 1000;
        return distance;
    }
}
